package fun.qu_an.minecraft.mini_games_helper.client.mixin;

import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.world.ClientWorld;
import net.minecraft.entity.decoration.DisplayEntity;
import net.minecraft.util.TypeFilter;
import net.minecraft.util.function.LazyIterationConsumer;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;

import java.util.concurrent.CompletableFuture;

@Environment(EnvType.CLIENT)
@Mixin(MinecraftClient.class)
public class MinecraftClient_ResourcepackEntityNameFix {
	@Inject(method = "reloadResources(ZLnet/minecraft/client/MinecraftClient$LoadingContext;)Ljava/util/concurrent/CompletableFuture;", at = @At(
		value = "RETURN"
	), cancellable = true)
	private void fixDisplayEntityTranslationDoesNotUpdate(boolean force, MinecraftClient.@Nullable LoadingContext loadingContext, CallbackInfoReturnable<CompletableFuture<Void>> cir) {
		CompletableFuture<Void> then = cir.getReturnValue().thenAccept(v -> {
			MinecraftClient client = MinecraftClient.getInstance();
			client.execute(() -> {
				ClientWorld clientWorld = client.world;
				if (clientWorld == null) {
					return;
				}
				clientWorld.entityManager.getLookup().forEach(TypeFilter.instanceOf(DisplayEntity.TextDisplayEntity.class),
					e -> {
						e.renderingDataSet = true;
						return LazyIterationConsumer.NextIteration.CONTINUE;
					});
			});
		});
		cir.setReturnValue(then);
	}
}
